//
//  WGCoreDataManager.m
//  WorkGo
//
//  Created by 李树志 on 2017/9/30.
//  Copyright © 2017年 李树志. All rights reserved.
//

#import "WGCoreDataManager.h"
#import <UIKit/UIKit.h>

static NSString *const CoreDataModelName = @"WorkGo";

@implementation WGCoreDataManager

+ (instancetype)sharedManager {
    static WGCoreDataManager *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[WGCoreDataManager alloc] init];
    });
    return _instance;
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDoucumentsDirectory {
    return [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].lastObject;
}

- (NSManagedObjectModel *)managedObjectModel {
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:CoreDataModelName withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDoucumentsDirectory] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", CoreDataModelName]];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"WorkGo" code:9999 userInfo:dict];
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"Error"
                                                         message:failureReason
                                                        delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertV show];
    }
    
    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    
    return _managedObjectContext;
}


#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = [self managedObjectContext];
    if (context != nil) {
        NSError *error = nil;
        if ([context hasChanges] && ![context save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"Error"
                                                             message:@"Core Data Save Failed!"
                                                            delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertV show];
        }
    }
}

@end
